/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aviso.services;

import aviso.entity.ScheduledMailRecord;
import aviso.facade.ScheduledMailRecordFacade;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Timer;
import javax.ejb.EJB;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.TimerService;

/**
 *
 * @author avgusti
 */
@Singleton
@Startup
public class MailSender {

    @Resource
    TimerService timerService;
    @EJB
    ScheduledMailRecordFacade mailRecordFacade;
    public static final long initial = 1000L * 60L;
    public static final long duration = 1000L * 60L;

    @PostConstruct
    public void init() {
        timerService.createTimer(initial, duration, null);
        
    }

    @Timeout
    public void SendScheduled(Timer timer) {
        //Logger.getAnonymousLogger().info("mail schedule tick");
        List<ScheduledMailRecord> mailRecords = mailRecordFacade.getEmailsToSend();
        for (ScheduledMailRecord record : mailRecords) {
            Logger.getAnonymousLogger().log(Level.INFO, "{0}:{1}", new Object[]{record.getMessageTo(), record.getMessageBody()});
            record.setSent(true);
            mailRecordFacade.edit(record);
        }
    }
}
